package com.fjrcloud.service;

import com.fjrcloud.dao.IdentifiedLandDao;
import com.fjrcloud.entity.HouseholdMaster;
import com.fjrcloud.entity.IdentifiedLand;
import com.fjrcloud.entity.LandStandard;
import com.fjrcloud.exception.BusinessException;
import com.fjrcloud.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * Created by shengjian.lin on 2017/1/22.
 */
@Service
public class IdentifiedLandService {

    @Autowired
    private IdentifiedLandDao identifiedLandDao;
    @Autowired
    private HouseholdService householdService;
    @Autowired
    private LandStandardService standardService;

    public IdentifiedLand save(Integer id, Integer masterId, Integer standardId, Double area, String description) throws BusinessException {

        HouseholdMaster master = findMaster(masterId);

        if (standardId == null)
            throw new BusinessException("认定标准错误");
        LandStandard standard = standardService.get(standardId);
        if (standard == null)
            throw new BusinessException("认定标准错误");

        if (area == null)
            throw new BusinessException("面积错误");

        IdentifiedLand identified;
        if (id == null)
            identified = new IdentifiedLand();
        else
            identified = identifiedLandDao.findOne(id);

        if (identified == null)
            throw new BusinessException("无效的保存对象");

        identified.setMaster(master);
        identified.setStandard(standard);
//        identified.setCare(care);
//        identified.setPrice(price);
        identified.setArea(area);
        identified.setDescription(description);
        identified.setCreateTime(System.currentTimeMillis());

        return identifiedLandDao.save(identified);
    }

    private HouseholdMaster findMaster(Integer masterId) throws BusinessException {
        if (masterId == null)
            throw new BusinessException("无效认证主体信息");
        HouseholdMaster master = householdService.getMaster(masterId);
        if (master == null)
            throw new BusinessException("无效认证主体信息");

        return master;
    }
    private PageRequest findPage(Integer pageNum, Integer pageSize) {
        pageNum = PageUtils.checkPageNum(pageNum);
        pageSize = PageUtils.checkPageSize(pageSize);
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);

        return pageRequest;
    }
    public Page<IdentifiedLand> find(Integer masterId,Integer pageNum, Integer pageSize) throws BusinessException {

        return identifiedLandDao.findByValidAndMasterOrderByCreateTimeAsc(true,findMaster(masterId),findPage(pageNum,pageSize));

    }
    public IdentifiedLand get(Integer id){
        return identifiedLandDao.findOne(id);
    }

    public void del(Integer id){
        identifiedLandDao.delete(id);
    }
}
